package com.shaoshaohuo.app.view;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.SpecificationAdapter;
import com.shaoshaohuo.app.adapter.VarietyGridviewAdapter;
import com.shaoshaohuo.app.constant.EcOption;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.EcCategorySecond;
import com.shaoshaohuo.app.entity.EcCategoryThird;
import com.shaoshaohuo.app.entity.EcVarietyEntity;
import com.shaoshaohuo.app.entity.Specification;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.ui.ec.BuysGoodsActivity;
import com.shaoshaohuo.app.ui.ec.ProductTypeActivity;
import com.shaoshaohuo.app.ui.ec.SelectSpecificationsActivity;
import com.shaoshaohuo.app.utils.SpecificationDataUtil;
import com.shaoshaohuo.app.utils.ViewUtil;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自定义 商品控件
 *
 * @author cao
 */
public class BuyProduct extends FrameLayout implements View.OnClickListener, OnItemClickListener {

    private BuysGoodsActivity mActivity; // 所属 activity
    private LinearLayout mLayoutProduct;
    private TextView mProductView; // 产品名称
    private TextView mPinZhongView; // 产品种类
    private GridView mSelectView; //
    private View layout_specifications;
    private EditText mNumberView; // 数量
    private LinearLayout mLayoutUnit;
    private TextView mUnitView; // 数量 单位

    private  MeasureGridView gv_specification;
  private FrameLayout  fl_specification;


    private ImageView mOpenView; // 打开选择产品 种类 gridView

    private Map<Specification, List<Specification>> selectSpecification = new HashMap<>();

    private int height; // gridView 高度
    private boolean isAnim = false; // 动画是否正在运行
    private boolean isOpen = false; // 当前 grid view 状态

    private AlertDialog unitDialog; // 单位选择 对话框
    protected String unit = "斤";// 存储单位

    private EcCategorySecond ecCategorySecond;// 选中的商品名称
    protected EcCategoryThird selectVariety;// 选中的 商品品种
    private ArrayList<EcCategoryThird> mSelectVarietyList = new ArrayList<>();// 当前请求回来的品种
    private VarietyGridviewAdapter<EcCategoryThird> mVarietyAdapter; // gridview//
    // 的适配器

    private ImageButton mAddView; // 向下 添加一个的 按钮
    private ImageButton mDeleteView; // 删除 自身按钮
    private TextView mAddText; //
    private TextView mDeleteText;

    public BuyProduct(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public BuyProduct(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public BuyProduct(Context context) {
        super(context);
        mActivity = (BuysGoodsActivity) context;
        View.inflate(context, R.layout.view_buy_product, this);
        initView();
        initData();
    }

    private void initView() {
        mLayoutProduct = (LinearLayout) findViewById(R.id.layout_product);
        mProductView = (TextView) findViewById(R.id.edittext_product);
        mPinZhongView = (TextView) findViewById(R.id.tv_pinzhong);
        mSelectView = (GridView) findViewById(R.id.gv_pinzhong);
        layout_specifications =  findViewById(R.id.layout_specifications);
        mNumberView = (EditText) findViewById(R.id.edittext_buy_count);
        mLayoutUnit = (LinearLayout) findViewById(R.id.layout_buy_unit);
        mUnitView = (TextView) findViewById(R.id.textview_buy_unit);
        mAddView = (ImageButton) findViewById(R.id.ib_add);
        mDeleteView = (ImageButton) findViewById(R.id.ib_delete);
        mOpenView = (ImageView) findViewById(R.id.iv_open);
        mAddText = (TextView) findViewById(R.id.tv_add_text);
        mDeleteText = (TextView) findViewById(R.id.tv_delete_text);

        gv_specification = (MeasureGridView) findViewById(R.id.gv_specification);
        fl_specification = (FrameLayout) findViewById(R.id.fl_specification);
        fl_specification.setVisibility(View.GONE);
    }

    private void initData() {
        mLayoutProduct.setOnClickListener(this);
        mLayoutUnit.setOnClickListener(this);
        mOpenView.setOnClickListener(this);
        mSelectView.setOnItemClickListener(this);

        setSpecificationClick();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_product:// 跳转到 产品名称 选择页面
                selectProduct();
                break;
            case R.id.layout_buy_unit:
                selectUnit();
                break;
            case R.id.iv_open:
                if (isOpen)
                    close();
                else
                    open();
                break;
        }
    }


    /**
     * 选择品种
     */
    private void selectSpecifications() {
        Intent intent = new Intent(mActivity, SelectSpecificationsActivity.class);
        intent.putExtra(ExtraName.ecCategoryThird, selectVariety);
        ViewGroup parent = (ViewGroup) getParent();
        int index = parent.indexOfChild(this);
        mActivity.startActivityForResult(intent, 100 + index);
    }

    public void getEntity() {

    }

    /**
     * 暴露给 add 按钮添加 点击事件的方法
     *
     * @param listener
     */
    public void setAddOnClickListener(OnClickListener listener) {
        if (listener != null) {
            mAddView.setOnClickListener(listener);
            mAddText.setOnClickListener(listener);
        }

    }

    /**
     * 给删除按钮 添加点击事件
     *
     * @param listener
     */
    public void setDeleteOnClickListener(OnClickListener listener) {
        if (listener != null) {
            mDeleteView.setOnClickListener(listener);
            mDeleteText.setOnClickListener(listener);
        }
    }

    public void setSpecificationClick(){
        layout_specifications.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //选择产品
                if (selectVariety == null) {
                    mActivity.showToast("请先选择品种");
                    return;
                } else {
                    selectSpecifications();
                }
            }
        });
        gv_specification.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //选择产品
                if (selectVariety == null) {
                    mActivity.showToast("请先选择品种");
                    return;
                } else {
                    selectSpecifications();
                }
            }
        });

    }

    /**
     * 隐藏add按钮
     */
    public void goneAddView() {
        mAddView.setVisibility(View.GONE);
        mAddText.setVisibility(View.GONE);
    }

    /**
     * 显示add按钮
     */
    public void visibleAddView() {
        mAddView.setVisibility(View.VISIBLE);
        mAddText.setVisibility(View.VISIBLE);

    }

    /**
     * 隐藏delete按钮
     */
    public void goneDeleteView() {
        mDeleteView.setVisibility(View.GONE);
        mDeleteText.setVisibility(View.GONE);
    }

    /**
     * 显示delete按钮
     */
    public void visibleDeleteView() {
        mDeleteView.setVisibility(View.VISIBLE);
        mDeleteText.setVisibility(View.VISIBLE);

    }

    /**
     * 弹框 让用户选择 单位
     */
    protected void selectUnit() {
        if (unitDialog != null && unitDialog.isShowing()) {
            return;
        }
        if (unitDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
            builder.setItems(EcOption.UNIT, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    unit = EcOption.UNIT[which];
                    mUnitView.setText(EcOption.UNIT[which]);
                }
            });
            unitDialog = builder.create();
            unitDialog.setTitle("单位");
        }
        unitDialog.show();
    }

    /**
     * 当请求的activity 返回后 需要在 所在activity 的 onActivityResult（）方法中回调该方法
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == mActivity.RESULT_OK) {

                EcCategorySecond second = (EcCategorySecond) data.getSerializableExtra(ExtraName.ecCategorySecond);
                if (ecCategorySecond != null && !TextUtils.isEmpty(ecCategorySecond.getCatid())
                        && ecCategorySecond.getCatid().equals(second.getCatid())) {
                } else {

                    if (ecCategorySecond != null && second.getCatname().equals("全部")
                            && ecCategorySecond.getCatname().equals("全部")) {
                        return;
                    }
                    ecCategorySecond = second;
                    mProductView.setText(ecCategorySecond.getCatname());
                    getVariety(ecCategorySecond);


            }

        }else if (resultCode == SelectSpecificationsActivity.SELECT_OK) {
            selectSpecification = (Map<Specification, List<Specification>>) data.getSerializableExtra(ExtraName.isForResult);
            if (!selectSpecification.isEmpty()) {

                gv_specification.setAdapter(new SpecificationAdapter(mActivity, gv_specification, selectSpecification));
                fl_specification.setVisibility(View.VISIBLE);
                layout_specifications.setVisibility(View.GONE);
            }else{
                fl_specification.setVisibility(View.GONE);
                layout_specifications.setVisibility(View.VISIBLE);
            }
        }
    }

    // 选择 产品名称
    private void selectProduct() {
        Intent intent = new Intent(mActivity, ProductTypeActivity.class);
        intent.putExtra(ExtraName.action, true);
        ViewGroup parent = (ViewGroup) getParent();
        int index = parent.indexOfChild(this);
        mActivity.startActivityForResult(intent, 100 + index);
    }

    // 跟据 选择 产品 名称 请求网络 获取 产品 种类
    private void getVariety(EcCategorySecond item) {
        mActivity.startLoadingDialog();
        RequestService.getInstance().getEcCategoryVariety(mActivity, item.getBigpid(), item.getCatid(),
                EcVarietyEntity.class, new RequestListener() {

                    @Override
                    public void onSuccess(int requestCode, BaseEntity resultData) {
                        mActivity.dismissLoadingDialog();
                        if (resultData.isOk()) {
                            EcVarietyEntity entity = (EcVarietyEntity) resultData;
                            mSelectVarietyList = (ArrayList<EcCategoryThird>) entity.getData().getList();
                            setVarietyAdapter();
                        } else {
                            mActivity.showToast(resultData.getMsg());
                        }
                    }

                    @Override
                    public void onFailed(int requestCode, Exception error, String msg) {
                        mActivity.dismissLoadingDialog();
                        mActivity.showToast(R.string.please_check_network);
                    }
                });
    }

    // 根据请求回来的 品种 集合 填充gridview
    protected void setVarietyAdapter() {
        mVarietyAdapter = new VarietyGridviewAdapter<>(mActivity, mSelectVarietyList, false);
        mVarietyAdapter.setSingleSeletion(true);
        mSelectView.setAdapter(mVarietyAdapter);
        // mSelectView.measure(0, 0);
        // height = mSelectView.getMeasuredHeight();
        // open();
        ObjectAnimator.ofFloat(mOpenView, "rotation", 0, 180).setDuration(250).start();
//		isOpen = true;// 因为 动态获取 gridView 的高度 不准确 所以 现在让它自己 通过adapter 填充 来展开
        // 当关闭时 已经填充满了 所以可以拿到高度
        open();
        mPinZhongView.setText("");
        mPinZhongView.setVisibility(View.GONE);

    }

    // gridview 的条目点击事件 当点击一个条目是 隐藏 gridview 并显示 选中的view
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        selectVariety = (EcCategoryThird) parent.getItemAtPosition(position);
        mPinZhongView.setVisibility(View.VISIBLE);
        mPinZhongView.setText(selectVariety.getCatname());
        mVarietyAdapter.setSelectPosition(position);
        close();
    }

    /**
     * 打开 gridView
     */
    public void open() {
        height = measureHeight(mSelectView);
        if (isAnim || height == 0)
            return;
        final ValueAnimator animator = ValueAnimator.ofInt(-height, 0);
        animator.addUpdateListener(new AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mSelectView.setPadding(0, (int) animator.getAnimatedValue(), 0, 0);
                mSelectView.requestLayout();
            }
        });
        animator.setDuration(250);
        animator.addListener(new AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                ObjectAnimator.ofFloat(mOpenView, "rotation", 0, 180).setDuration(250).start();
                isAnim = true;
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                isAnim = false;
                isOpen = true;
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }
        });
        mSelectView.setVisibility(View.VISIBLE);
        animator.start();
    }

    /**
     * 关闭gridView
     */
    public void close() {
//		height = mSelectView.getMeasuredHeight();
        height = measureHeight(mSelectView);
        if (isAnim || height == 0)
            return;
        final ValueAnimator animator = ValueAnimator.ofInt(0, -height);
        animator.addUpdateListener(new AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mSelectView.setPadding(0, (int) animator.getAnimatedValue(), 0, 0);
                mSelectView.requestLayout();
            }
        });
        animator.setDuration(250);
        animator.addListener(new AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                ObjectAnimator.ofFloat(mOpenView, "rotation", 180, 360).setDuration(250).start();
                isAnim = true;
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                isAnim = false;
                isOpen = false;
                mSelectView.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }
        });
        animator.start();
    }

    //	测量  gridview 高度
    public int measureHeight(GridView gridView) {
        int count = gridView.getChildCount();
        int rowCount = count / 3 + (count % 3 == 0 ? 0 : 1);
        View childView = gridView.getAdapter().getView(0, null, null);
//		View childView =  gridView.getChildAt(0);
        childView.measure(0, 0);
        int height = childView.getMeasuredHeight();
        int verticalSpacing = ViewUtil.dip2px(mActivity, 5f);
        return height * rowCount + (rowCount - 1) * verticalSpacing;
    }

    public boolean check() {
        return ecCategorySecond != null && selectVariety != null && !TextUtils.isEmpty(getNum()) && !TextUtils.isEmpty(unit);
    }

    /**
     * 返回选择商品的名称
     *
     * @return
     */
    public EcCategorySecond getSecond() {
        return ecCategorySecond;
    }

    /**
     * 返回选择商品的 品种
     *
     * @return
     */
    public EcCategoryThird getThird() {
        return selectVariety;
    }

    /**
     * 返回商品的数量
     *
     * @return
     */
    public String getNum() {
        return mNumberView.getText().toString().trim();
    }

    /**
     * 返回商品的 单价
     */
    public String getUnit() {
        return unit;
    }

    /**
     * 返回商品的规格
     *
     * @return
     */
    public String getGuige() {
        String str = "";
        if(!selectSpecification.isEmpty()){
            Collection<List<Specification>> values = selectSpecification.values();
            for (List<Specification> list : values) {
                for (Specification specification : list) {
                    str += specification.id + ",";
                }
            }
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }

    public void setUnit(String unit) {
        this.unit = unit;
        mUnitView.setText(unit);
    }

    public void setEcCategorySecond(EcCategorySecond ecCategorySecond) {
        this.ecCategorySecond = ecCategorySecond;
        mProductView.setText(ecCategorySecond.getCatname());
    }

    public void setSelectVariety(EcCategoryThird selectVariety) {
        this.selectVariety = selectVariety;
        mPinZhongView.setText(selectVariety.getCatname());
        mPinZhongView.setVisibility(View.VISIBLE);
    }

    public void setmNumberView(String mNumber) {
        this.mNumberView.setText(mNumber);
    }

    public void setmGuigeView(List<Specification> specifications) {
        selectSpecification = SpecificationDataUtil.list2map(specifications);

        if (!selectSpecification.isEmpty()) {
            gv_specification.setAdapter(new SpecificationAdapter(mActivity, gv_specification, selectSpecification));
            fl_specification.setVisibility(View.VISIBLE);
            layout_specifications.setVisibility(View.GONE);
        } else {
            fl_specification.setVisibility(View.GONE);
            layout_specifications.setVisibility(View.VISIBLE);
        }

    }
}
